package com.smarthospital.service.impl;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.smarthospital.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * create by sym  2021/5/19 20:55.
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Value("${fdfs.hostPort}")
    private String dfsHostProt;

    //文件上传到HDFS
    @Override
    public String fileUpload(MultipartFile file) throws Exception {
        return upload(file);
    }

    @Resource
    private FastFileStorageClient storageClient ;
    /**
     * 上传文件
     */
    private String upload(MultipartFile multipartFile) throws Exception{
        String originalFilename = multipartFile.getOriginalFilename().
                substring(multipartFile.getOriginalFilename().
                        lastIndexOf(".") + 1);
        StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
                multipartFile.getInputStream(),
                multipartFile.getSize(),originalFilename.toUpperCase() , null);
        String fullPath = storePath.getFullPath();

        return dfsHostProt + fullPath ;
    }

    /**
     * 上传文件
     */
    @Override
    public String upload(InputStream inputStream,String fileExtName,long size){

        StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
                inputStream, size,fileExtName, null);
        String fullPath = storePath.getFullPath();

        return dfsHostProt + fullPath ;
    }
    /**
     * 删除文件
     */
    private void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            log.info("fileUrl == >>文件路径为空...");
            return;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }
}
